/*******************************************************************
* Posledni modifikace:  12.1.2011,0:56                             *
********************************************************************/
<?php

require_once("Auth.php");

class RizaUtilsClass
{
    public $last_insert_id;
    public $row_affected;
    public $error_msg;
    public $last_sql_command;


// constructor
function RizaUtilsClass($dsn)
{

$pripojeni = $this->parseDSN($dsn);

$hostname_connect = $pripojeni['hostspec'];
$database_connect = $pripojeni['database'];
$username_connect = $pripojeni['username'];
$password_connect = $pripojeni['password'];
$connect = mysql_pconnect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);

mysql_query("SET NAMES 'latin1';"); //nebo 'latin2' nebo 'utf8'


}


/*******************************************************************
* FUNKCE:  parseDSN()                                              *
* TRIDA:   -                                                       *
* VSTUP:   retezec pro pripojeni do DB                             *
*          mysql://username:password@hostitel/nazev_database       *
********************************************************************/
function parseDSN($dsn)
{
    $parsed = array(
        'phptype'  => false,
        'dbsyntax' => false,
        'username' => false,
        'password' => false,
        'protocol' => false,
        'hostspec' => false,
        'port'     => false,
        'socket'   => false,
        'database' => false,
    );

    if (is_array($dsn)) {
        $dsn = array_merge($parsed, $dsn);
        if (!$dsn['dbsyntax']) {
            $dsn['dbsyntax'] = $dsn['phptype'];
        }
        return $dsn;
    }

    // Find phptype and dbsyntax
    if (($pos = strpos($dsn, '://')) !== false) {
        $str = substr($dsn, 0, $pos);
        $dsn = substr($dsn, $pos + 3);
    } else {
        $str = $dsn;
        $dsn = null;
    }

    // Get phptype and dbsyntax
    // $str => phptype(dbsyntax)
    if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
        $parsed['phptype']  = $arr[1];
        $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
    } else {
        $parsed['phptype']  = $str;
        $parsed['dbsyntax'] = $str;
    }

    if (!count($dsn)) {
        return $parsed;
    }

    // Get (if found): username and password
    // $dsn => username:password@protocol+hostspec/database
    if (($at = strrpos($dsn,'@')) !== false) {
        $str = substr($dsn, 0, $at);
        $dsn = substr($dsn, $at + 1);
        if (($pos = strpos($str, ':')) !== false) {
            $parsed['username'] = rawurldecode(substr($str, 0, $pos));
            $parsed['password'] = rawurldecode(substr($str, $pos + 1));
        } else {
            $parsed['username'] = rawurldecode($str);
        }
    }

    // Find protocol and hostspec

    if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
        // $dsn => proto(proto_opts)/database
        $proto       = $match[1];
        $proto_opts  = $match[2] ? $match[2] : false;
        $dsn         = $match[3];

    } else {
        // $dsn => protocol+hostspec/database (old format)
        if (strpos($dsn, '+') !== false) {
            list($proto, $dsn) = explode('+', $dsn, 2);
        }
        if (strpos($dsn, '/') !== false) {
            list($proto_opts, $dsn) = explode('/', $dsn, 2);
        } else {
            $proto_opts = $dsn;
            $dsn = null;
        }
    }

    // process the different protocol options
    $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
    $proto_opts = rawurldecode($proto_opts);
    if (strpos($proto_opts, ':') !== false) {
        list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
    }
    if ($parsed['protocol'] == 'tcp') {
        $parsed['hostspec'] = $proto_opts;
    } elseif ($parsed['protocol'] == 'unix') {
        $parsed['socket'] = $proto_opts;
    }

    // Get dabase if any
    // $dsn => database
    if ($dsn) {
        if (($pos = strpos($dsn, '?')) === false) {
            // /database
            $parsed['database'] = rawurldecode($dsn);
        } else {
            // /database?param1=value1&param2=value2
            $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
            $dsn = substr($dsn, $pos + 1);
            if (strpos($dsn, '&') !== false) {
                $opts = explode('&', $dsn);
            } else { // database?param1=value1
                $opts = array($dsn);
            }
            foreach ($opts as $opt) {
                list($key, $value) = explode('=', $opt);
                if (!isset($parsed[$key])) {
                    // don't allow params overwrite
                    $parsed[$key] = rawurldecode($value);
                }
            }
        }
    }

    return $parsed;
}


/*******************************************************************
* FUNKCE:  da(DisplayArray)                                              *
* TRIDA:   -                                                       *
* VSTUP:   retezec pro pripojeni do DB                             *
*          mysql://username:password@hostitel/nazev_database       *
********************************************************************/
function da($array)
{
    echo  "<pre>";
    print_r($array);
    echo "</pre>";
}



/*******************************************************************
* FUNKCE:  ExecSQL($sql)                                           *
* TRIDA:   -                                                       *
* VSTUP:   vykona SQL prikaz                                       *
* VRACI:   false v pripade neuspechu
 *         true pokud OK
********************************************************************/
function ExecSQL($sql)
{
  $result = mysql_query($sql);
  $p = mysql_affected_rows();
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $sql;
    //$_SESSION['messageError'] = $message;
    $this->da($message);
    return false;
    //return $message;
}
if ($p==0) return false;
$this->last_insert_id = mysql_insert_id();
return true;
}

/*******************************************************************
* FUNKCE:  ExecSQL($sql)                                           *
* TRIDA:   -                                                       *
* Vstup:   sql dotaz                                               *
* Vystup:  vraci prvni zaznam                                      *
********************************************************************/
function retSQLExec($query)
{
    $result=mysql_query($query)or die(mysql_error());
    $num_fields = mysql_num_fields($result);
    $j=0;
    $x=1;
    if (!$result) return FALSE;
    while($row=mysql_fetch_array($result)){
      for($j=0;$j<$num_fields;$j++){
       $name = mysql_field_name($result, $j);
       $object[$x][$name]=$row[$name];
      }$x++;
}
return $object[1];
}



/*******************************************************************
* FUNKCE:  ExecSQL($sql)                                           *
* TRIDA:   -                                                       *
* Popis:
* Vstup:   tabulka, pole ve formatu $pole[sloupec] = hodnota       *
* Vystup:  vraci prvni zaznam                                      *
********************************************************************/
/*
function mysql_insert_array ($my_table, $my_array) {
    $keys = array_keys($my_array);
    $values = array_values($my_array);
    $this->last_sql_command = 'INSERT INTO ' . $my_table . '(' . implode(',', $keys) . ') VALUES ("' . implode('","', $values) . '")';
    $ret = mysql_query($this->last_sql_command);
    
    if (!$ret) $this->error_msg = mysql_error();
        else
    return $ret;
}*/


/*******************************************************************
* FUNKCE:  Exequote_valcSQL($sql)                                  *
* TRIDA:   -                                                       *
* Depedency: mysql_insert_into                                     *
********************************************************************/
function quote_val($val, $strict_value = false)
{
	//Setting unquoted values.
	$unquoted[] = 'NULL';
	$unquoted[] = 'NOW()';

	if ($strict_value or !in_array(strtoupper($val), $unquoted))
	{
		$val = "'".$val."'";
	}

	return $val;
}


/*******************************************************************
* FUNKCE:  GetTablesValues                                       OK*
* TRIDA:   -                                                       *
* Popis:   vraci vsechny zaznamy z tabulky                         *
* Vstup:   nazev tabulky, podminky                                 *
* Vystup:  vraci prvni zaznam                                      *
********************************************************************/
function GetTablesValues($tables, $condition='')
{
    if ($tables=="")
    $query = sprintf($condition);
    else  $query = sprintf("SELECT * from %s", mysql_real_escape_string($tables).' '.$condition);

    $this->last_sql_command = $query;

    $result = mysql_query($query);

    if (!$result)
        $this->error_msg = mysql_error();
    else
    {
        $num_fields = mysql_num_fields($result);
        $j=0;
        $x=1;
        while($row=mysql_fetch_array($result))
        {
          for($j=0;$j<$num_fields;$j++){
           $name = mysql_field_name($result, $j);
           $object[$x][$name]=$row[$name];
          }$x++;
        }
        if (isset($object)) return $object;
    }
return false;
}


/*******************************************************************
* FUNKCE:  mysql_insert_into                                     OK*
* TRIDA:   -                                                       *
* vstup:   tabulka, pole ve formatu $pole[sloupec] = hodnota       *
* Popis:   vraci vsechny zaznamy z tabulky                         *
* Vraci:   true/false                                              *
********************************************************************/
function mysql_insert_into($table_name, $param_array, $strict_values = false, $mysql_escape = false)
{
	//Aborting if table name or param array are empty.
	if (empty($table_name) or !is_array($param_array)) return false;

	//Prepering array contruction.
	if (!is_array($param_array[0])) $input[0] = $param_array;
	else $input = $param_array;

	//Building query columns and values to insert into the query string.
	foreach ($input as $array => $index)
	{
		$query_string_values_tmp = '';
		$query_string_values .= ', (';
		foreach ($index as $key => $val)
		{
			if (strlen($key))
			{
				if ($mysql_escape)
				{
					$val = mysql_real_escape_string($val);
					if (!$query_string_columns_done) $key = mysql_real_escape_string($key);
				}

				$val = $this->quote_val($val, $strict_values);

				$query_string_values_tmp .= ", $val";
				if (!$query_string_columns_done) $query_string_columns .= ", `$key`";
			}
		}

		$query_string_columns_done = true;
		if (!empty($query_string_values_tmp)) $query_string_values .= substr($query_string_values_tmp, 2);
		$query_string_values .= ')';
	}

	if (strlen($query_string_columns) > 2)
	{
		//Building query string.
		$query_string_columns = substr($query_string_columns, 2);
		$query_string_values = substr($query_string_values, 2);
		$query_string = "INSERT INTO $table_name ($query_string_columns) VALUES $query_string_values";

                $this->last_sql_command = $query_string;

		if (mysql_query( $this->last_sql_command ))
		{
			//Returning the insert id or true, depending on the function input.
			$this->last_insert_id = mysql_insert_id();
                        //$result = ($return_id) ? $this->last_insert_id : true;
			return true;
		}
                else $this->error_msg = mysql_error();

	}

	//returning false if param array was empty or query failed for some reason.
	return false;
}







}




  /* *****************************************************************************
  * Posledni uprava: 18.4.2010, verze 1.01
  * TRIDA:  RizaMessages                                18/02/2010              *
  * VSTUP:  pomoci konstruktora dojde k inicializaci                            *
  *         promenne salt, ktera urcuje hash pro ukladani SESSION.              *
  * POPIS:  funkce PushMessages(),FlushMessages, pro zachytavani textu          *
  *         pres register $_SESSION                                             *
  *******************************************************************************/
class RizaMessages
{
  private $salt;

  function __construct($salt)
  {
		/*if (DEBUG_ENABLED)
			debug_log('Entered with (%s)',17,__FILE__,__LINE__,__METHOD__,$server_id);
			*/
                  if (session_name()=='')
                 {
                     //var_dump($_REQUEST);
                     session_start();
                 }
    $this->salt = "ClassRizaMessages".$salt;
	}

	function GetSalt()
	{
    return "ClassRizaMessages".$this->salt;
  }

  function __destruct()
  {
   //unset($_SESSION[$this->salt]);
  }

  /*******************************************************************************
  * METODA:  FlushMessages                                18/02/2010             *
  * VSTUP:   $clear - true = vymaze z bufferu                                    *
  * POPIS:   vraci vsechny zpravy z bufferu                                      *
  *******************************************************************************/
  function FlushMessages($clear = true, $typ = 'error')
  {
    $ret = $_SESSION[$this->salt][$typ];
    if ($clear) unset($_SESSION[$this->salt][$typ]);
    return $ret;
  }

  function FlushMessagesHTML($clear = true,$typ = 'all')
  {
    $x = "";
    if ($typ=='all')
    {
    if (isset( $_SESSION[$this->salt][$typ]))
        if (($ret = $_SESSION[$this->salt][$typ]) !=NULL)
        foreach ($ret as $key => $value)
            foreach ($value as $data)
            $x .= $data."<br/>";
    }
    else
    {
    if (isset( $_SESSION[$this->salt][$typ]))
        if (($ret = $_SESSION[$this->salt][$typ]) !=NULL)
        foreach ($ret as $value)
        $x .= $value."<br/>";
    }

    //if ($clear) unset($_SESSION[$this->salt][$typ]);
    return $x;
  }


  function CacheOut()
  {
    unset($_SESSION[$this->salt]);
  }


  function PushMessage($string="", $typ = 'error')
  {
    //echo "salt".$this->salt;
    $_SESSION[$this->salt][$typ][] = $string;
  }
} //class RizaMessages




class RizaAutorizace extends Auth
{

function isLogged()
{
//    echo "<h2>jsme tu</h2>";
    print_r($this->getAuthData());
    if ($this->getAuthData('id')>0) return $this->getAuthData('id');
    else  return false;
}

function getPrava()
{
    return $this->getAuthData('prava');
}

function getUsername()
{
    return $this->getAuthData('user');

}

}



?>
